﻿using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;

namespace K9Nano.Serialization;

/// <summary>
/// 统一JSON序列化的参数
/// </summary>
public static class JsonHelper
{
    private static readonly JsonSerializerOptions Default;

    private static readonly JsonSerializerOptions Ordered;

    static JsonHelper()
    {
        Default = new JsonSerializerOptions(JsonSerializerDefaults.Web)
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            ReferenceHandler = ReferenceHandler.IgnoreCycles,
        };

        Ordered = new JsonSerializerOptions(JsonSerializerDefaults.Web)
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            ReferenceHandler = ReferenceHandler.IgnoreCycles,
            TypeInfoResolver = new DefaultJsonTypeInfoResolver
            {
                Modifiers = { OrderProperties }
            },
        };
    }

    private static void OrderProperties(JsonTypeInfo typeInfo)
    {
        if (typeInfo.Kind != JsonTypeInfoKind.Object)
            return;

        // 将属性按名称排序
        var orderedProperties = typeInfo.Properties
            .OrderBy(p => p.Name, StringComparer.Ordinal)
            .ToList();

        // 清空原属性集合并重新添加排序后的属性
        typeInfo.Properties.Clear();
        foreach (var property in orderedProperties)
        {
            typeInfo.Properties.Add(property);
        }
    }

    public static string Serialize(object data)
    {
        return JsonSerializer.Serialize(data, Default);
    }

    public static T? Deserialize<T>(string json)
    {
        return JsonSerializer.Deserialize<T>(json, Default);
    }

    /// <summary>
    /// 将属性按名称排序进行序列化
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static string SerializeOrdered(object data)
    {
        return JsonSerializer.Serialize(data, Ordered);
    }
}